// HTTP客户端配置
import axios, { type AxiosInstance, type AxiosResponse, type AxiosRequestConfig } from 'axios'
import type { ApiResponse } from '@/types'
import { useUserStore } from '@/stores/user'
import { ElMessage } from 'element-plus'

// 创建axios实例
const axiosInstance: AxiosInstance = axios.create({
  baseURL: import.meta.env.VITE_API_BASE_URL,
  timeout: Number(import.meta.env.VITE_API_TIMEOUT) || 100000,
  headers: {
    'Content-Type': 'application/json',
  },
})

// 请求拦截器
axiosInstance.interceptors.request.use(
  async (config) => {
    const userStore = useUserStore()
    //  判断是否登录
    if (!userStore.isAuthenticated && !config.url?.includes('/login') && !config.url?.includes('mockLogin')) {
      const res = await userStore.login()
      if (!res) {
        throw new Error('请先登录！')
      }
    }
    // 添加认证token
    const token = userStore.token
    if (token) {
      config.headers.Authorization = `${token}`
    }
    return config
  },
  (error) => {
    return Promise.reject(error)
  },
)

// 响应拦截器 - 只处理HTTP错误，不改变返回类型
axiosInstance.interceptors.response.use(
  (response: AxiosResponse<ApiResponse>) => {
    return response
  },
  (error) => {
    const userStore = useUserStore()
    // 处理HTTP错误
    if (error.response) {
      const { status } = error.response
      switch (status) {
        case 401:
        case 2002:
          // 未授权，清除token并跳转登录
          localStorage.removeItem('token')
          userStore.logout()
          userStore.login()
          ElMessage.error('登录已过期，请重新登录')
          break
        case 403:
          ElMessage.error('权限不足')
          break
        case 404:
          ElMessage.error('请求的资源不存在')
          break
        case 500:
          ElMessage.error('服务器内部错误')
          break
        default:
          ElMessage.error('请求失败:', error.message)
      }
    } else {
      ElMessage.error('网络错误:', error.message)
    }

    return Promise.reject(error)
  },
)

// 自定义请求函数，返回 ApiResponse 数据
async function request<T = any>(config: AxiosRequestConfig): Promise<ApiResponse<T>> {
  const response = await axiosInstance<ApiResponse<T>>(config)
  const { data,status } = response

  // 统一处理业务逻辑
  if (data.code === 200) {
    return data
  } else if (data.code === 401 || data.code === 2002) {
    ElMessage.error('登录已过期，请重新登录')
    // 清除用户信息并跳转登录页
    const userStore = useUserStore()
    userStore.logout()
    userStore.login()
    throw new Error('登录已过期')
  } else if (status === 200) {
    return response
  } else {
    // 处理业务错误
    ElMessage.error(data.message || '请求失败')
    throw new Error(data.message || '请求失败')
  }
}

export default request
